<template>
  <div class="app-container custom" v-loading="loading">
    <el-form :model="queryParams" :inline="true" style="width: 1607px;">
          <el-form-item label="日期" prop="dataTime" label-width="40px">
            <WeekTimePicker type="date" :options="disabledOptions" v-model="queryParams.dataTime" :clearable="false" style="width: 130px"/>
          </el-form-item>

          <el-form-item label="选择设备">
            <el-checkbox-group v-model="queryParams.selectedEpt" :min="1" :max="2">
              <el-checkbox v-for="group in groups" :key="group" :label="group">{{ group }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="选择功能">
            <el-checkbox-group v-model="queryParams.selectedFun">
              <el-checkbox label="produce" disabled>生产</el-checkbox>
              <el-checkbox label="warnMethod" @change="warnMethod">报警</el-checkbox>
              <el-checkbox label="edit" @change="editTable">批注</el-checkbox>
            </el-checkbox-group>
            <el-button style="margin-left: 10px;" type="primary" icon="Search" @click="getQueryData">查询</el-button>
            <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="!summaryList.tableData.length"
                        @click="editMethod"
                >编辑</el-button>

                <el-button>{{ countdown }} s</el-button>
          </el-form-item>
          <p style="float: right; margin: 5px 5px 0 0; color: red;">※ 生产量统计时间段区分逻辑同工厂班次一致，即8:30表示 8:30-9:30，其他时间段依此类推</p>
    </el-form>

    <!-- SummaryList -->
    <!-- :style="{height: summaryList.tableData.length * 33 + 37 + 'px'}" -->
    <t-ag-grid
      style="height: 131px;"
      class="add-margin"
      :column-defs="firstTable"
      :row-data="summaryList.tableData"
      :row-buffer="20"
      align="center"
      :defaultColDef = "{
        suppressMenu:true
      }"
      header-align="center"
    />

    <!-- 图例说明 -->
    <div style="width: 1607px; margin-bottom: 48px;">
      <img src="@/assets/images/legend.jpg" style="display: block; width: 100%; height: 28px; float: right;" />
    </div>

      <template v-for="(firstFloor, index) in monitorEqpInfoList.dataValue">
          <div class="title-chart" style="margin-top: 20px;">
            <div>
              <span class="main-title" @click="routerJump(firstFloor.topId)">{{ firstFloor.topId }}</span>
              <el-tooltip
                effect="dark"
                :content="monitorEqpInfoList.isShowPools.find((x) => x.kes === firstFloor.topId)?.values % 2 === 0 ? '隐藏子设备' : '显示子设备'"
                placement="top"
                raw-content
                :enterable="false"
                transition=""
                :hide-after="0"
                :open-delay="20">
                <el-button circle :icon="monitorEqpInfoList.isShowPools.find((x) => x.kes === firstFloor.topId)?.values % 2 === 0 ? 'ArrowUp' : 'ArrowDown'" @click="getIsShow(firstFloor.topId)" plain style="margin-left: 20px;"/>
              </el-tooltip>
            </div>
            <div class="chartContent">
              <div ref="myChart" class="my-chart" v-if="chartIsMount">{{ firstFloor.topId }}</div>
            </div>
          </div>
          <t-ag-grid
            class="add-margin"
            :style="{height: [firstFloor.oeeBEqpProductSummary].length * 33 + 34 + 'px'}"
            :column-defs="summaryList.column"
            :row-data="[{...firstFloor.oeeBEqpProductSummary, productionTarget: '产量'}]"
            :row-buffer="20"
            align="center"
            :defaultColDef = "{
              suppressMenu:true
            }"
            header-align="center"
          />

          <t-ag-grid
            class="add-margin"
            v-if="firstFloor.oeeBEqpMaterialSummaryList.length"
            :style="{height: firstFloor.oeeBEqpMaterialSummaryList.length * 34 + 'px'}"
            :column-defs="monitorEqpInfoList.mainEqpSecondGrid.column"
            :row-data="firstFloor.oeeBEqpMaterialSummaryList"
            :row-buffer="20"
            :header-height="0"
            align="center"
            :defaultColDef = "{
              suppressMenu:true
            }"
            header-align="center"
          />

            <div v-for="(chilEqp, index) in firstFloor.oeeMonitorDetailInfoList" v-show="monitorEqpInfoList.isShowPools.find((x) => x.kes === firstFloor.topId)?.values % 2 === 0">
              <div style="margin: 10px 0 0 0 ;">
                <div class="title-chart">
                  <div>
                    <el-button
                         type="danger"
                         plain
                         icon="Sort"
                         @click="getIsShow(chilEqp.machineId)"
                         style="opacity: 0;"
                      >展开/折叠</el-button>
                      <span class="child-title">{{ chilEqp.oeeBEqpProductSummary.machineId }}</span>
                  </div>
                  <div class="chartContent">
                    <div ref="myChart" class="my-chart" v-if="chartIsMount">{{ chilEqp.oeeBEqpProductSummary.machineId }}</div>
                  </div>
                </div>
              </div>

              <t-ag-grid
                :style="{height: [chilEqp.oeeBEqpProductSummary].length * 33 + 34 + 'px'}"
                class="add-margin"
                :column-defs="summaryList.column"
                :row-data="[{...chilEqp.oeeBEqpProductSummary, productionTarget: '产量'}]"
                :row-buffer="20"
                align="center"
                :defaultColDef = "{
                  suppressMenu:true
                }"
                header-align="center"
              />

              <t-ag-grid
                :style="{height: chilEqp.oeeBEqpMaterialSummaryList.length * 34 + 'px'}"
                class="add-margin"
                :column-defs="monitorEqpInfoList.mainEqpSecondGrid.column"
                :row-data="chilEqp.oeeBEqpMaterialSummaryList"
                :row-buffer="20"
                :header-height="-10"
                align="center"
                :defaultColDef = "{
                  suppressMenu:true
                }"
                header-align="center"
              />
            </div>

            <t-ag-grid
              style="height: 226px;"
              class="add-margin"
              v-if="selectFun.alarm && firstFloor.oeeBEqpAlarmList.length"
              :column-defs="alarmColumn"
              :row-data="firstFloor.oeeBEqpAlarmList"
              :row-buffer="20"
              align="center"
              :defaultColDef = "{
                suppressMenu:true
              }"
              header-align="center"
            />

            <t-ag-grid
              style="height: 131px;"
              class="add-margin"
              v-if="selectFun.edit && firstFloor.oeeBEqpDescriptionList.length"
              :column-defs="describeColumn"
              :row-data="firstFloor.oeeBEqpDescriptionList"
              :row-buffer="20"
              align="center"
              :defaultColDef = "{
                suppressMenu:true
              }"
              header-align="center"
            />

      </template>

      <el-dialog v-model="selectFun.open" :close-on-click-modal="false" width="1000px" append-to-body>
        <el-form ref="editRef" :model="queryParams" :rules="rules">
          <el-form-item label="设备名称" prop="businessType">
            <el-select
                   v-model="queryParams.businessType"
                   placeholder="请选择设备名称"
                   clearable
                   style="width: 200px"
                   @change="editSelectValChange"
                >
                   <el-option
                      v-for="dict in queryParams.options"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                   />
                </el-select>

          </el-form-item>
        </el-form>
            <t-ag-grid
              style="height: 355px;"
              class="add-margin"
              :column-defs="editTableColumn"
              :row-data="editQueryParams.tableData"
              :row-buffer="20"
              align="center"
              :defaultColDef = "{
                suppressMenu:true
              }"
              header-align="center"
              row-selection="multiple"
              :suppress-row-click-selection="true"
              :row-multi-select-with-click="true"
              @cellEditingStopped="cellEditingStopped"
              @grid-ready="onGridReady"
              />
              <template #footer>
                <span style="float: left; color: red;">提示：请手动 √ 勾选需要保存内容后再点击"确定"，未勾选内容在点击"确定"后自动删除</span>
                <div class="dialog-footer">
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
      </el-dialog>

  </div>
</template>

<script setup name="MBB">
  import { listSummary as getList, getSavedMsg, saveEditApi } from '@/api/PRDMonitor/beforeLayer'
  import useAppStore from "@/store/modules/app"
  import moment from 'moment'
  import { getActionColumn, alarmColumn, describeColumn, editTableColumn, editTableData, firstTable } from './config'
  import { chartOptios } from './chart'
  import { nextTick, onActivated, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { cloneDeep } from 'lodash'
  import { getPRDMonitorOptions } from '@/common/affect'
  import * as echarts from 'echarts'

  const router = useRouter()
  const { proxy } = getCurrentInstance()
  const appStore = useAppStore()

  const loading = ref(false)
  const countdown = ref(180)
  const openCountdown = ref(false)
  const queryParams =  reactive({
    dataTime: moment().format('YYYY-MM-DD'),
    selectedEpt: ['1区'],
    selectedFun: ['produce'],
    options: [
      // { label: 'qwe', value: 'qwe' },
      // { label: 'asd', value: 'asd' },
      // { label: 'zxc', value: 'zc' }
    ],
    businessType: null
  })
  const summaryList = reactive({
    column: [],
    tableData: []
  })

  const monitorEqpInfoList = reactive({
    isShowPools: [],
    dataValue: null,
    mainEqpSecondGrid: {
      // topId: '',
      column: [],
      tableData: []
    },
    chilEqpOne: {
      // topId: '',
      column: [],
      tableData: []
    },
    chilEqpTwo: {
      // topId: '',
      column: [],
      tableData: []
    }
  })

  const selectFun = reactive({
    alarm: false,
    edit: false,
    open: false
  })

  const editQueryParams = reactive({
    tableData: cloneDeep(editTableData)
  })

  const groups = ref()
  const myChart = ref()

  appStore.toggleOpened(false)
  onActivated(() => {
    appStore.toggleOpened(false)
  })

  const materialSecondGrid = [
    { headerName: "", field: "materialCode", width: 126 },
    { headerName: "", field: "ttl", width: 85 },
    { headerName: "", field: "ttTarget", width: 75 }
  ]

  const gridApi = ref()

  let chart = null
  let chartIsMount = ref(true)

  const onGridReady = ({ api }) => {
    gridApi.value = api
  }

  const rules =  {
    businessType: [
      { required: true, message: "设备名称不能为空", trigger: "change" }
    ]
  }

  const disabledOptions = {
    disabledDate (date) {
      return date && date.valueOf() > moment().valueOf()
    }
  }

  let timer = null

  onActivated(() => {
    if(history?.state?.selectedEpt?.length && history?.state?.dataTime){
      queryParams.selectedEpt = history?.state?.selectedEpt
      queryParams.dataTime = history?.state?.dataTime
      getQueryData()
    }
  })

  const getQueryData = () => {
    if(moment(moment(queryParams.dataTime).format('YYYY-MM-DD 08:30:00')).unix() >  moment().unix()){
      proxy.$modal.alertError(`时间选择不正确 请重新选择!`)
      return
    }
    loading.value = true
    chartIsMount.value = false
    getList({
      areaList: queryParams.selectedEpt,
      dataTime: moment(queryParams.dataTime).format('YYYY-MM-DD'),
      process: 'MBB'
    }).then(({ oeeBProductionSummaryList, oeeMonitorEqpInfoListList, oeeBMachineEchartsList }) => {
      countdown.value = 180
      chartIsMount.value = true
      loading.value = false
      summaryList.column = getActionColumn(oeeBProductionSummaryList)
      summaryList.tableData = oeeBProductionSummaryList
      if(moment(moment(queryParams.dataTime).format('YYYY-MM-DD 08:30:00')).unix() < moment(moment().format('YYYY-MM-DD HH:mm:ss')).unix() && moment(moment().format('YYYY-MM-DD HH:mm:ss')).unix() < moment(moment(queryParams.dataTime).add(1, 'days').format('YYYY-MM-DD 08:30:00')).unix()){
        openCountdown.value = true
      } else {
        openCountdown.value = false
      }

      monitorEqpInfoList.mainEqpSecondGrid.column = getActionColumn(oeeMonitorEqpInfoListList[0].oeeBEqpMaterialSummaryList, materialSecondGrid, 27)
      monitorEqpInfoList.dataValue = oeeMonitorEqpInfoListList
      nextTick(() => {
        myChart.value?.forEach((item, index) => {
          if(moment(moment(queryParams.dataTime).format('YYYY-MM-DD 08:30:00')).unix() < moment(moment().format('YYYY-MM-DD HH:mm:ss')).unix() && moment(moment().format('YYYY-MM-DD HH:mm:ss')).unix() < moment(moment(queryParams.dataTime).add(1, 'days').format('YYYY-MM-DD 08:30:00')).unix()){
            const diffVal =  moment(moment().format('YYYY-MM-DD HH:mm:ss')).unix() - moment(moment(queryParams.dataTime).format('YYYY-MM-DD 08:00:00')).unix()
            item.style.width = `${((diffVal / 3600) * 55) - 27.5}px`
          }
          item.mark = item.innerText
          chart = echarts.init(item)
          echarts.getInstanceByDom(item).setOption(chartOptios(oeeBMachineEchartsList, item.mark, index, moment(queryParams.dataTime).format('YYYY-MM-DD')))
        })
      })

      queryParams.options = []
      oeeMonitorEqpInfoListList.forEach((item) => {
        queryParams.options.push({
          label: item.topId,
          value: item.topId
        })
      })
    })
  }

  const getIsShow = (params) => {
    let findVal = monitorEqpInfoList.isShowPools.find((item) => item.kes === params )
    if(monitorEqpInfoList.isShowPools.length && findVal){
      findVal.values ++
    } else {
      monitorEqpInfoList.isShowPools.push({
        kes: params,
        values: 2
      })
    }

  }

  const warnMethod = (val) => {
    selectFun.alarm = val
  }

  const editTable = (val) => {
    selectFun.edit = val
  }

  const editMethod = () => {
    if(summaryList.tableData.length){
      selectFun.open = true
      queryParams.businessType && (queryParams.businessType = null)
      editQueryParams.tableData = cloneDeep(editTableData)
    }
  }

  const editSelectValChange = (val) => {
    getSavedMsg({
      machineId: val,
      dataTime: moment(queryParams.dataTime).format('YYYY-MM-DD')
    }).then((msg) => {
      editQueryParams.tableData = [...msg.rows, ...cloneDeep(editTableData)]
      nextTick(() => {
        const nodes = gridApi.value.getRenderedNodes()
        const selectedNodes = nodes.filter((node) => {
          if(node.data.textEditing){
            return node.data.textEditing
          }
        })
        selectedNodes.forEach(function(node) {
          node.setSelected(true)
        })
      })
    })
  }

  const cellEditingStopped = (params) => {
    nextTick(() => {
      const nodes = gridApi.value.getRenderedNodes()
      const selectedNodes = nodes.filter((node) => {
        if(node.data.textEditing){
          return node.data.textEditing
        }
      })
      selectedNodes.forEach(function(node) {
        node.setSelected(true)
      })
    })
  }

  const saveEdit = () => {
    proxy.$refs.editRef.validate(valid => {
      if (valid) {
        const _parm = []
        if(!gridApi.value.getSelectedRows().length){
          proxy.$modal.alertWarning(`请选择要保存的内容！`)
          return
        }

        proxy.$modal.confirm('请手动 √ 勾选需要保存内容后再点击"确定"，未勾选内容在点击"确定"后自动删除').then(function () {
          gridApi.value.getSelectedRows().forEach( item => {
            _parm.push({
              "createBy": item.createBy,
              "createTime": item.createTime,
              "dataTime": moment(queryParams.dataTime).format('YYYY-MM-DD'),
              "dept": "",
              "duration": "",
              "endTime": "",
              "machineId": queryParams.businessType,
              "params": {},
              "remark": item.textEditing,
              "startTime": "",
              "textEditing": "",
              "updateBy": "",
              "updateTime": ""
            })
          })
          saveEditApi(_parm).then((res) => {
            selectFun.open = false
            getQueryData()
          })
        })

      }
    })
  }

  const cancel = () => {
    selectFun.open = false
    editQueryParams.tableData = [{}, {}]
  }

  const routerJump = (topId) => {
    router.push({
      path: '/timeAnalysis/history',
      state: {
        dataTime: queryParams.dataTime,
        machineTypeId: topId
      }
    })
  }

  watch(() => openCountdown.value, (val, preVal) => {
    if(val){
      timer = setInterval(() => {
        countdown.value--
        if(countdown.value === 0 && location.pathname.includes('MBB')){
          getQueryData()
        } else if(countdown.value === 0) {
          countdown.value = 180
        }
      }, 1000)
    } else {
      window.clearInterval(timer)
    }
  })

  document.addEventListener('visibilitychange', () => {
    var isHidden = document.hidden
    if (isHidden) {
      window.clearInterval(timer)
    } else {
      if(openCountdown.value){
        openCountdown.value = false
        setTimeout(() => {
          openCountdown.value = true
        }, 0)
      }
    }
  }, true)

  onUnmounted(() => {
    document.addEventListener('visibilitychange', () => {
      var isHidden = document.hidden
      if (isHidden) {
        window.clearInterval(timer)
      } else {
        if(openCountdown.value){
          openCountdown.value = false
          setTimeout(() => {
            openCountdown.value = true
          }, 0)
        }
      }
    }, true)
  })

  getPRDMonitorOptions({
    type: 'MBB'
  }).then((res) => {
    groups.value = res.rows
  })

  if(!history?.state?.dataTime){
    getQueryData()
  }

</script>

<style scoped lang="less">
.custom {
  overflow-y: scroll;

  .add-margin{
    margin-bottom: 10px;
    width: 1607px !important;
  }
  .title-chart{
    display: flex;
    justify-content: space-between;
    width: 1607px;
    .main-title{
      font-size: 16px;
      color: blue;
      line-height: 28px;
      width: 220px;
    }

    .main-title:hover {
      cursor: pointer;
    }

    .chartContent{
      width: 1322px;
      height: 28px;
      background: #eeeeee;

      .my-chart{
        width: 1322px;
        height: 28px;
      }
    }
  }
  .child-title {
    color: blue;
    margin-left: 10px;
    line-height: 28px;
  }

  .child-title:hover {
    cursor: pointer;
  }
}
.el-checkbox {
  margin-right: 7px;
}

:deep(.ag-root-wrapper) {
  // border-top: none !important;
}

.el-dialog__header {
  padding: 0px !important;
}
.el-dialog__body{
  padding-top: 0px !important;
}
</style>